﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class DeliverGoodsManagement_AddSettlement : System.Web.UI.Page
{
    private DataTable TempDataTable
    {
        get
        {
            DataTable tempTable = null;
            if (ViewState["TempDataTable"] != null)
            {
                tempTable = (DataTable)ViewState["TempDataTable"];
            }
            return tempTable;
        }
        set
        {
            ViewState["TempDataTable"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Check.CheckPermission("700100");
        if (!IsPostBack)
        {
            btnCancel.Attributes.Add("onclick", "if(!confirm('要取消新建结算单并返回上一页吗?'))return false;");
        }

        Session["FCode"] = "700100";

    }

    private void BindDataListOrder(string customerId)
    {
        DataSet dstOrder = new BLL.ORDERDOC().GetCustomerOrders(customerId);
        DataSet dstReturnDoc = new BLL.RETURNDOC().GetReturnDocByCustomerId(customerId);
        DataSet dst = new BLL.PAYDOC().JoinDataTable(dstOrder, dstReturnDoc);
        if (dst != null)
        {
            if (dst.Tables.Count > 0)
            {
                if (dst.Tables[0].Rows.Count > 0)
                {
                    dlistOrder.DataSource = dst;
                    dlistOrder.DataBind();
                }
                else
                {
                    dlistOrder.DataSource = null;
                    dlistOrder.DataBind();
                }
            }
        }
    }

    private void BindDropPayType(string dealType, DropDownList drop)
    {
        DataSet dst = new BLL.PAYTYPE_DEALTYPE().P_DealType_GetPayTypeByCode(dealType);
        ListItem tempItem;
        drop.Items.Clear();
        for (int i = 0; i < dst.Tables[0].Rows.Count; i++)
        {
            tempItem = new ListItem();
            tempItem.Text = dst.Tables[0].Rows[i]["PT_NAME"].ToString();
            tempItem.Value = dst.Tables[0].Rows[i]["PT_CODE"].ToString() + "|" + dst.Tables[0].Rows[i]["PT_HAVEDEAL"].ToString();
            drop.Items.Add(tempItem);
        }

    }

    protected void btnChooseCustomer_Click(object sender, EventArgs e)
    {
        if (txtUserCode.Text.Trim() != "" && dropSettlementType.SelectedIndex == 0)
        {
            BindDataListOrder(txtUserCode.Text.Trim());
        }
        else
        {
            dlistOrder.DataSource = null;
            dlistOrder.DataBind();

        }
        txtPayAmount.Text = "0.00";
        this.TempDataTable = null;
        BindDataListPayDocPayDetail(this.TempDataTable);
    }

    protected void dropSettlementType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (txtUserCode.Text.Trim() != "" && dropSettlementType.SelectedIndex == 0)
        {
            BindDataListOrder(txtUserCode.Text.Trim());
        }
        else
        {
            dlistOrder.DataSource = null;
            dlistOrder.DataBind();

        }
        txtPayAmount.Text = "0.00";
        this.TempDataTable = null;
        BindDataListPayDocPayDetail(this.TempDataTable);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtUserCode.Text.Trim() != "")
            {

                if (new BLL.PAYDOC().ValidCustomerHasUncheckedPayDoc(txtUserCode.Text.Trim()))
                {
                    //Share.Alert(this.Page, "该会员有未经核准的结算单,不能再为其新建结算单！");
                    ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('该会员有未经核准的结算单,不能再为其新建结算单！')", true);
                    return;
                }
                else
                {
                    FillValueIntoDataTable(this.TempDataTable);

                    if (Convert.ToDecimal(txtPayAmount.Text.Trim()) != 0 && this.TempDataTable == null)
                    {
                        ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('请添加支付明细！')", true);
                        return;
                    }

                    if (dropSettlementType.SelectedIndex == 0)
                    {
                        switch (ValidBalance(this.TempDataTable))
                        {
                            case 0:
                                break;
                            case 1:
                                //Share.Alert(this.Page, "未找到会员VIP信息！");
                                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('未找到会员VIP信息！')", true);
                                return;
                                break;
                            case 2:
                                //Share.Alert(this.Page, "未找到结余金额信息！");
                                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('未找到结余金额信息！')", true);
                                return;
                                break;
                            case 3:
                                //Share.Alert(this.Page, "结余金额不足！!");
                                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('结余金额不足！')", true);
                                return;
                                break;
                            case 4:
                                break;
                        }
                        if (ValidSettleAmount(this.TempDataTable, Convert.ToDecimal(txtReceiveMoneyAmount.Text.Trim())))
                        {
                            List<Model.PAYDOCDETAIL> payDetails = new List<Model.PAYDOCDETAIL>();
                            Model.PAYDOCDETAIL detail;

                            CheckBox checkRow;
                            Label lblDealType;
                            Label lblOrderId;
                            Label lblCreateDate;
                            Label lblTotal;
                            Label lblClearAmount;
                            TextBox txtCurrentClearAMT;
                            foreach (DataListItem tempItem in dlistOrder.Items)
                            {
                                checkRow = (CheckBox)tempItem.FindControl("checkRow");
                                if (checkRow.Checked)
                                {
                                    lblDealType = (Label)tempItem.FindControl("lblDealType");
                                    lblOrderId = (Label)tempItem.FindControl("lblOrderId");
                                    lblCreateDate = (Label)tempItem.FindControl("lblCreateDate");
                                    lblTotal = (Label)tempItem.FindControl("lblTotal");
                                    lblClearAmount = (Label)tempItem.FindControl("lblClearAmount");
                                    txtCurrentClearAMT = (TextBox)tempItem.FindControl("txtCurrentClearAMT");

                                    detail = new Model.PAYDOCDETAIL();
                                    detail.PDD_DOCTYPE = lblDealType.Text == "订单" ? "001" : "002";   //001表示订单，002表示退货单
                                    detail.PDD_DOCID = lblOrderId.Text;
                                    detail.PDD_DOCDATE = Convert.ToDateTime(lblCreateDate.Text);
                                    detail.PDD_TAMT = Convert.ToDecimal(lblTotal.Text);
                                    detail.PDD_CLEAREDAMT = Convert.ToDecimal(lblClearAmount.Text);
                                    detail.PDD_AMT = Convert.ToDecimal(txtCurrentClearAMT.Text.Trim());
                                    detail.PDD_SUBAMT = detail.PDD_TAMT - detail.PDD_CLEAREDAMT - detail.PDD_AMT;

                                    payDetails.Add(detail);
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            if (payDetails.Count > 0)
                            {
                                string newPayDocId;
                                bool result = InsertPayDoc(txtUserCode.Text.Trim(), dropSettlementType.SelectedItem.Value, Convert.ToDecimal(txtReceiveMoneyAmount.Text.Trim()), Convert.ToDecimal(txtPayAmount.Text.Trim()), payDetails, this.TempDataTable, out newPayDocId);
                                if (result)
                                {
                                    //Response.Write("<script>alert('新建结算单成功！');window.location.href='SettlementDetails.aspx?code=" + newPayDocId + "'</script>");
                                    ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('新建结算单成功！');window.location.href='SettlementDetails.aspx?code=" + newPayDocId + "'", true);
                                }
                                else
                                {
                                    //Share.Alert(this.Page, "新建结算单时出现错误，请重新创建！");
                                    ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('新建结算单时出现错误，请重新创建！')", true);
                                }
                            }
                            else
                            {
                                //Share.Alert(this.Page, "请选择需要结算的单据！");
                                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('请选择需要结算的单据！')", true);
                            }
                        }
                        else
                        {
                            //Share.Alert(this.Page, "支付金额必须大于或等于结算金额，请核对后重试！");
                            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('支付金额必须大于或等于结算金额，请核对后重试！')", true);
                        }

                    }
                    else
                    {
                        for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                        {
                            if (this.TempDataTable.Rows[i]["PDPD_PAYTYPE"].ToString() == "200")
                            {
                                //Share.Alert(this.Page, "预收款支付方式不能选择账户余额！");
                                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('预收款支付方式不能选择账户余额！')", true);
                                return;
                            }
                        }
                        string newPayDocId;
                        bool result = InsertPayDoc(txtUserCode.Text.Trim(), dropSettlementType.SelectedItem.Value, Convert.ToDecimal(txtReceiveMoneyAmount.Text.Trim()), Convert.ToDecimal(txtPayAmount.Text.Trim()), null, this.TempDataTable, out newPayDocId);
                        if (result)
                        {
                            //Response.Write("<script>alert('新建结算单成功！');window.location.href='SettlementDetails.aspx?code=" + newPayDocId + "'</script>");
                            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('新建结算单成功！');window.location.href='SettlementDetails.aspx?code=" + newPayDocId + "'", true);
                        }
                        else
                        {
                            //Share.Alert(this.Page, "新建结算单时出现错误，请重新创建！");
                            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('新建结算单时出现错误，请重新创建！')", true);
                        }
                    }


                }
            }
            else
            {
                //Share.Alert(this.Page, "请选择会员！");
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('请选择会员！')", true);
            }
        }
        catch (Exception ex)
        {
            //Share.Alert(this.Page, ex.Message);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('" + ex.Message + "')", true);
        }
    }

    public bool InsertPayDoc(string customerId, string settlementTypeId, decimal payAmount, decimal settleAmount, List<Model.PAYDOCDETAIL> payDetails, DataTable tblPayDocPayDetail, out string payDocId)
    {
        if (settlementTypeId == "001")
        {
            string newPayDocId = new SQLServerDAL.PAYDOC().GetNewPayDocID();
            BLL.Common.ADDLSH("700100");
            if (newPayDocId != null)
            {

                StringBuilder strSql = new StringBuilder();

                strSql.Append("INSERT INTO [PAYDOC]([PD_ID],[PD_DATE],[PD_AID],[PD_CUSTOMERCODE],[PD_CLEARTYPE],");
                strSql.Append("[PD_CAMT],[PD_PAMT],[PD_SUBAMT],[PD_CREATER],[PD_CREATEDATE]) values('");
                strSql.Append(newPayDocId);
                strSql.Append("','");
                strSql.Append(DateTime.Now);
                strSql.Append("','");
                strSql.Append("");
                strSql.Append("','");
                strSql.Append(customerId);
                strSql.Append("','");
                strSql.Append(settlementTypeId);
                strSql.Append("',");
                strSql.Append(settleAmount);
                strSql.Append(",");
                strSql.Append(payAmount);
                strSql.Append(",");
                strSql.Append(payAmount - settleAmount);
                strSql.Append(",'");
                strSql.Append("");  //制单人

                strSql.Append("','");
                strSql.Append(DateTime.Now);  //制单日期
                strSql.Append("')|");

                for (int i = 0; i < payDetails.Count; i++)
                {
                    strSql.Append("INSERT INTO [PAYDOCDETAIL]([PDD_ID],[PDD_DETAILID],[PDD_DOCTYPE],[PDD_DOCID],");
                    strSql.Append("[PDD_DOCDATE],[PDD_TAMT],[PDD_CLEAREDAMT],[PDD_AMT],[PDD_SUBAMT]) VALUES('");
                    strSql.Append(newPayDocId);
                    strSql.Append("','");
                    strSql.Append(Convert.ToString(i + 1));
                    strSql.Append("','");
                    strSql.Append(payDetails[i].PDD_DOCTYPE);
                    strSql.Append("','");
                    strSql.Append(payDetails[i].PDD_DOCID);
                    strSql.Append("','");
                    strSql.Append(payDetails[i].PDD_DOCDATE);
                    strSql.Append("',");
                    strSql.Append(payDetails[i].PDD_TAMT);
                    strSql.Append(",");
                    strSql.Append(payDetails[i].PDD_CLEAREDAMT);
                    strSql.Append(",");
                    strSql.Append(payDetails[i].PDD_AMT);
                    strSql.Append(",");
                    strSql.Append(payDetails[i].PDD_TAMT - payDetails[i].PDD_CLEAREDAMT - payDetails[i].PDD_AMT);
                    strSql.Append(")|");
                }

                if (tblPayDocPayDetail != null)
                {
                    for (int i = 0; i < tblPayDocPayDetail.Rows.Count; i++)
                    {
                        strSql.Append("INSERT INTO [PAYDOCPAYDETAIL]([PDPD_ID],[PDPD_PAYDETAILID],[PDPD_PAYTYPE],[PDPD_PAYAMT],");
                        strSql.Append("[PDPD_PAYDATE],[PDPD_DEALID],[PDPD_DEALDATE],[PDPD_ACCOUNT],[PDPD_NOTE],[PDPD_DTCODE]) VALUES('");
                        strSql.Append(newPayDocId);
                        strSql.Append("','");
                        strSql.Append(Convert.ToString(i + 1));
                        strSql.Append("','");
                        strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_PAYTYPE"].ToString());
                        strSql.Append("',");
                        strSql.Append(Convert.ToDecimal(tblPayDocPayDetail.Rows[i]["PDPD_PAYAMT"]));
                        strSql.Append(",'");
                        strSql.Append(Convert.ToDateTime(tblPayDocPayDetail.Rows[i]["PDPD_PAYDATE"]));
                        strSql.Append("','");
                        strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_DEALID"].ToString());
                        strSql.Append("','");
                        strSql.Append(Convert.ToDateTime(tblPayDocPayDetail.Rows[i]["PDPD_DEALDATE"]));
                        strSql.Append("','");
                        strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_ACCOUNT"].ToString());
                        strSql.Append("','");
                        strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_NOTE"].ToString());
                        strSql.Append("','");
                        strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_DTCODE"].ToString());
                        strSql.Append("')|");
                    }
                }

                //for (int i = 0; i < payDetails.Count; i++)
                //{
                //    if (payDetails[i].PDD_TAMT - payDetails[i].PDD_CLEAREDAMT - payDetails[i].PDD_AMT == 0)
                //    {
                //        strSql.Append("update ORDERDOC set ORDER_CLEARAMT=");
                //        strSql.Append(payDetails[i].PDD_TAMT);
                //        strSql.Append(", ORDER_CLEAR=1 where ORDER_ID='");
                //        strSql.Append(payDetails[i].PDD_DOCID);
                //        strSql.Append("'|");
                //    }
                //    else if (payDetails[i].PDD_TAMT - payDetails[i].PDD_CLEAREDAMT - payDetails[i].PDD_AMT > 0)
                //    {
                //        strSql.Append("update ORDERDOC set ORDER_CLEARAMT=");
                //        strSql.Append(payDetails[i].PDD_CLEAREDAMT + payDetails[i].PDD_AMT);
                //        strSql.Append(" where ORDER_ID='");
                //        strSql.Append(payDetails[i].PDD_DOCID);
                //        strSql.Append("'|");
                //    }
                //}


                if (new SQLServerDAL.ORDERDOC().Deliver(StringBuilderToStringArray(strSql)))
                {
                    payDocId = newPayDocId;
                    return true;
                }
                else
                {
                    payDocId = "";
                    return false;
                }
            }
            else
            {
                payDocId = "";
                return false;
            }
        }
        else if (settlementTypeId == "002")
        {
            string newPayDocId = new SQLServerDAL.PAYDOC().GetNewPayDocID();
            BLL.Common.ADDLSH("700100");
            if (newPayDocId != null)
            {
                Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(customerId);
                if (userInfo == null)
                {
                    throw new Exception("不存在该用户！");
                }
                Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);
                if (userAccount == null)
                {
                    StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                    StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                    strSqlToUpdateBStyleDB.Append("INSERT INTO [PAYDOC]([PD_ID],[PD_DATE],[PD_AID],[PD_CUSTOMERCODE],[PD_CLEARTYPE],");
                    strSqlToUpdateBStyleDB.Append("[PD_CAMT],[PD_PAMT],[PD_SUBAMT],[PD_CREATER],[PD_CREATEDATE]) values('");
                    strSqlToUpdateBStyleDB.Append(newPayDocId);
                    strSqlToUpdateBStyleDB.Append("','");
                    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                    strSqlToUpdateBStyleDB.Append("','");
                    strSqlToUpdateBStyleDB.Append("");
                    strSqlToUpdateBStyleDB.Append("','");
                    strSqlToUpdateBStyleDB.Append(customerId);
                    strSqlToUpdateBStyleDB.Append("','");
                    strSqlToUpdateBStyleDB.Append(settlementTypeId);
                    strSqlToUpdateBStyleDB.Append("',");
                    strSqlToUpdateBStyleDB.Append(settleAmount);
                    strSqlToUpdateBStyleDB.Append(",");
                    strSqlToUpdateBStyleDB.Append(payAmount);
                    strSqlToUpdateBStyleDB.Append(",");
                    strSqlToUpdateBStyleDB.Append(payAmount - settleAmount);
                    strSqlToUpdateBStyleDB.Append(",'");
                    strSqlToUpdateBStyleDB.Append("");  //制单人

                    strSqlToUpdateBStyleDB.Append("','");
                    strSqlToUpdateBStyleDB.Append(DateTime.Now);  //制单日期
                    strSqlToUpdateBStyleDB.Append("')|");

                    if (tblPayDocPayDetail != null)
                    {

                        for (int i = 0; i < tblPayDocPayDetail.Rows.Count; i++)
                        {
                            strSqlToUpdateBStyleDB.Append("INSERT INTO [PAYDOCPAYDETAIL]([PDPD_ID],[PDPD_PAYDETAILID],[PDPD_PAYTYPE],[PDPD_PAYAMT],");
                            strSqlToUpdateBStyleDB.Append("[PDPD_PAYDATE],[PDPD_DEALID],[PDPD_DEALDATE],[PDPD_ACCOUNT],[PDPD_NOTE],[PDPD_DTCODE]) VALUES('");
                            strSqlToUpdateBStyleDB.Append(newPayDocId);
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(Convert.ToString(i + 1));
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(tblPayDocPayDetail.Rows[i]["PDPD_PAYTYPE"].ToString());
                            strSqlToUpdateBStyleDB.Append("',");
                            strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(tblPayDocPayDetail.Rows[i]["PDPD_PAYAMT"]));
                            strSqlToUpdateBStyleDB.Append(",'");
                            strSqlToUpdateBStyleDB.Append(Convert.ToDateTime(tblPayDocPayDetail.Rows[i]["PDPD_PAYDATE"]));
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(tblPayDocPayDetail.Rows[i]["PDPD_DEALID"].ToString());
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(Convert.ToDateTime(tblPayDocPayDetail.Rows[i]["PDPD_DEALDATE"]));
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(tblPayDocPayDetail.Rows[i]["PDPD_ACCOUNT"].ToString());
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(tblPayDocPayDetail.Rows[i]["PDPD_NOTE"].ToString());
                            strSqlToUpdateBStyleDB.Append("','");
                            strSqlToUpdateBStyleDB.Append(tblPayDocPayDetail.Rows[i]["PDPD_DTCODE"].ToString());
                            strSqlToUpdateBStyleDB.Append("')|");
                        }


                    }

                    strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                    strSqlToUpdateBStyleDB.Append(userInfo.DM);
                    strSqlToUpdateBStyleDB.Append("',0)|");

                    strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                    strSqlToUpdateErpDB.Append(userInfo.DM);
                    strSqlToUpdateErpDB.Append("',0)|");


                    string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                    string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                    char[] charToTrim = new char[] { '|' };
                    string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                    string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                    LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                    bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                    if (result)
                    {
                        payDocId = newPayDocId;
                        return true;
                    }
                    else
                    {
                        payDocId = "";
                        return false;
                    }
                }
                else
                {
                    StringBuilder strSql = new StringBuilder();

                    strSql.Append("INSERT INTO [PAYDOC]([PD_ID],[PD_DATE],[PD_AID],[PD_CUSTOMERCODE],[PD_CLEARTYPE],");
                    strSql.Append("[PD_CAMT],[PD_PAMT],[PD_SUBAMT],[PD_CREATER],[PD_CREATEDATE]) values('");
                    strSql.Append(newPayDocId);
                    strSql.Append("','");
                    strSql.Append(DateTime.Now);
                    strSql.Append("','");
                    strSql.Append("");
                    strSql.Append("','");
                    strSql.Append(customerId);
                    strSql.Append("','");
                    strSql.Append(settlementTypeId);
                    strSql.Append("',");
                    strSql.Append(settleAmount);
                    strSql.Append(",");
                    strSql.Append(payAmount);
                    strSql.Append(",");
                    strSql.Append(payAmount - settleAmount);
                    strSql.Append(",'");
                    strSql.Append("");  //制单人

                    strSql.Append("','");
                    strSql.Append(DateTime.Now);  //制单日期
                    strSql.Append("')|");

                    if (tblPayDocPayDetail != null)
                    {
                        for (int i = 0; i < tblPayDocPayDetail.Rows.Count; i++)
                        {
                            strSql.Append("INSERT INTO [PAYDOCPAYDETAIL]([PDPD_ID],[PDPD_PAYDETAILID],[PDPD_PAYTYPE],[PDPD_PAYAMT],");
                            strSql.Append("[PDPD_PAYDATE],[PDPD_DEALID],[PDPD_DEALDATE],[PDPD_ACCOUNT],[PDPD_NOTE],[PDPD_DTCODE]) VALUES('");
                            strSql.Append(newPayDocId);
                            strSql.Append("','");
                            strSql.Append(Convert.ToString(i + 1));
                            strSql.Append("','");
                            strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_PAYTYPE"].ToString());
                            strSql.Append("',");
                            strSql.Append(Convert.ToDecimal(tblPayDocPayDetail.Rows[i]["PDPD_PAYAMT"]));
                            strSql.Append(",'");
                            strSql.Append(Convert.ToDateTime(tblPayDocPayDetail.Rows[i]["PDPD_PAYDATE"]));
                            strSql.Append("','");
                            strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_DEALID"].ToString());
                            strSql.Append("','");
                            strSql.Append(Convert.ToDateTime(tblPayDocPayDetail.Rows[i]["PDPD_DEALDATE"]));
                            strSql.Append("','");
                            strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_ACCOUNT"].ToString());
                            strSql.Append("','");
                            strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_NOTE"].ToString());
                            strSql.Append("','");
                            strSql.Append(tblPayDocPayDetail.Rows[i]["PDPD_DTCODE"].ToString());
                            strSql.Append("')|");
                        }
                    }

                    if (new SQLServerDAL.ORDERDOC().Deliver(StringBuilderToStringArray(strSql)))
                    {
                        payDocId = newPayDocId;
                        return true;
                    }
                    else
                    {
                        payDocId = "";
                        return false;
                    }
                }

            }
            else
            {
                payDocId = "";
                return false;
            }
        }
        payDocId = "";
        return false;

    }

    private string[] StringBuilderToStringArray(StringBuilder strSql)
    {
        string stringSql = strSql.ToString();
        char[] charToTrim = new char[] { '|' };
        return stringSql.TrimEnd(charToTrim).Split(charToTrim);
    }

    protected void dlistOrder_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            CheckBox checkRow = (CheckBox)e.Item.FindControl("checkRow");
            Button btnCheck = (Button)e.Item.FindControl("btnCheck");
            checkRow.Attributes.Add("onclick", btnCheck.ClientID + ".click();");
            TextBox txtCurrentClearAMT = (TextBox)e.Item.FindControl("txtCurrentClearAMT");
            Button btnUpdateCurrentClearAMT = (Button)e.Item.FindControl("btnUpdateCurrentClearAMT");
            txtCurrentClearAMT.Attributes.Add("onblur", btnUpdateCurrentClearAMT.ClientID + ".click();");
        }
    }

    protected void dlistOrder_ItemCommand(object source, DataListCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.ToLower() == "check")
            {
                CheckBox checkRow = (CheckBox)e.Item.FindControl("checkRow");
                TextBox txtCurrentClearAMT = (TextBox)e.Item.FindControl("txtCurrentClearAMT");
                Label lblTotal = (Label)e.Item.FindControl("lblTotal");
                Label lblClearAmount = (Label)e.Item.FindControl("lblClearAmount");
                Label lblSub = (Label)e.Item.FindControl("lblSub");
                if (checkRow.Checked)
                {
                    txtCurrentClearAMT.Visible = true;
                    lblSub.Text = Convert.ToString(Convert.ToDecimal(lblTotal.Text) - Convert.ToDecimal(lblClearAmount.Text) - Convert.ToDecimal(txtCurrentClearAMT.Text));
                }
                else
                {
                    txtCurrentClearAMT.Visible = false;
                    lblSub.Text = Convert.ToString(Convert.ToDecimal(lblTotal.Text) - Convert.ToDecimal(lblClearAmount.Text));
                }
                decimal payAmount = 0;
                foreach (DataListItem tempItem in dlistOrder.Items)
                {
                    CheckBox chkItem = (CheckBox)tempItem.FindControl("checkRow");
                    TextBox txtItem = (TextBox)tempItem.FindControl("txtCurrentClearAMT");
                    if (chkItem.Checked)
                    {
                        payAmount += Convert.ToDecimal(txtItem.Text.Trim());
                    }
                }
                txtPayAmount.Text = String.Format("{0:0.00}", payAmount);
            }

            else if (e.CommandName.ToLower() == "updatecurrentclearamt")
            {
                decimal payAmount = 0;
                foreach (DataListItem tempItem in dlistOrder.Items)
                {
                    CheckBox chkItem = (CheckBox)tempItem.FindControl("checkRow");
                    TextBox txtItem = (TextBox)tempItem.FindControl("txtCurrentClearAMT");
                    if (chkItem.Checked)
                    {
                        payAmount += Convert.ToDecimal(txtItem.Text.Trim());
                    }
                }
                txtPayAmount.Text = String.Format("{0:0.00}", payAmount);

                TextBox txtCurrentClearAMT = (TextBox)e.Item.FindControl("txtCurrentClearAMT");
                Label lblTotal = (Label)e.Item.FindControl("lblTotal");
                Label lblClearAmount = (Label)e.Item.FindControl("lblClearAmount");
                Label lblSub = (Label)e.Item.FindControl("lblSub");
                lblSub.Text = Convert.ToString(Convert.ToDecimal(lblTotal.Text) - Convert.ToDecimal(lblClearAmount.Text) - Convert.ToDecimal(txtCurrentClearAMT.Text));
            }
        }
        catch (Exception ex)
        {
            //Share.Alert(this.Page, ex.Message);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('" + ex.Message + "')", true);
        }
    }

    protected void btnAddPayDocPayDetail_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.TempDataTable == null)
            {
                this.TempDataTable = new BLL.PAYDOCPAYDETAIL().CreateTempDataTable();
            }
            else
            {
                FillValueIntoDataTable(this.TempDataTable);
            }

            BindDataListPayDocPayDetail(new BLL.PAYDOCPAYDETAIL().AddDataRowToDataTable(this.TempDataTable));
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('" + ex.Message + "')", true);
        }
    }

    protected void dlistPayDocPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList dropDealType = (DropDownList)e.Item.FindControl("dropDealType");
            for (int i = 0; i < dropDealType.Items.Count; i++)
            {
                if (dropDealType.Items[i].Value == this.TempDataTable.Rows[e.Item.ItemIndex]["PDPD_DTCODE"].ToString())
                {
                    dropDealType.SelectedIndex = i;
                    break;
                }
            }

            DropDownList dropPayType = (DropDownList)e.Item.FindControl("dropPayType");
            if (dropPayType != null)
            {
                if (this.TempDataTable.Rows[e.Item.ItemIndex]["PDPD_DTCODE"].ToString() != "")
                {
                    BindDropPayType(this.TempDataTable.Rows[e.Item.ItemIndex]["PDPD_DTCODE"].ToString(), dropPayType);
                    for (int i = 0; i < dropPayType.Items.Count; i++)
                    {
                        if (dropPayType.Items[i].Value.Contains(this.TempDataTable.Rows[e.Item.ItemIndex]["PDPD_PAYTYPE"].ToString() + "|"))
                        {
                            dropPayType.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    BindDropPayType(dropDealType.Items[0].Value, dropPayType);
                }
                

            }
            TextBox txtPayAmount = (TextBox)e.Item.FindControl("txtPayAmount");
            Button btnUpDatePayAmount = (Button)e.Item.FindControl("btnUpDatePayAmount");
            txtPayAmount.Attributes.Add("onblur", btnUpDatePayAmount.ClientID + ".click();");
        }
    }

    protected void dlistPayDocPayDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.ToLower() == "del")
            {
                FillValueIntoDataTable(this.TempDataTable);

                BindDataListPayDocPayDetail(new BLL.PAYDOCPAYDETAIL().SubDataRowFromDataTable(this.TempDataTable, e.Item.ItemIndex));

                CountAmount();
            }
            else if (e.CommandName.ToLower() == "upt")
            {
                CountAmount();
            }
        }
        catch (Exception ex)
        {
            //Share.Alert(this.Page, ex.Message);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('" + ex.Message + "')", true);
        }

    }

    private void CountAmount()
    {
        try
        {
            TextBox txtAmount;
            decimal payAmount = 0;
            for (int i = 0; i < dlistPayDocPayDetail.Items.Count; i++)
            {
                txtAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
                payAmount += Convert.ToDecimal(txtAmount.Text);
            }

            txtReceiveMoneyAmount.Text = String.Format("{0:0.00}", payAmount);
            txtBalance.Text = String.Format("{0:0.00}", payAmount - Convert.ToDecimal(txtPayAmount.Text));
        }
        catch (Exception ex)
        {
            //Share.Alert(this.Page, ex.Message);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('" + ex.Message + "')", true);
        }
    }

    private int ValidBalance(DataTable tbl)
    {
        decimal count = 0;
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            if (tbl.Rows[i]["PDPD_PAYTYPE"].ToString() == "200")
            {
                count += Convert.ToDecimal(tbl.Rows[i]["PDPD_PAYAMT"]);
            }
        }
        if (count == 0)
        {
            return 0;//表示未使用结余款支付
        }
        else
        {
            Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(txtUserCode.Text.Trim());
            if (userInfo == null)
            {
                return 1;//表示未找到会员VIP信息
            }
            Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);
            if (userAccount == null)
            {
                return 2; //表示未找到会员结余款信息
            }
            if (userAccount.DQJE_1 < count)
            {
                return 3;
            }
            return 4;
        }

    }

    private void FillValueIntoDataTable(DataTable tbl)
    {
        DropDownList dropDealType;
        DropDownList dropPayType;
        TextBox txtPayAmount;
        TextBox txtPayDate;
        TextBox txtDealID;
        TextBox txtDealDate;
        TextBox txtAccount;
        TextBox txtNotes;

        for (int i = 0; i < dlistPayDocPayDetail.Items.Count; i++)
        {
            dropDealType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropDealType");
            dropPayType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropPayType");
            txtPayAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
            txtPayDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayDate");
            txtDealID = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealID");
            txtDealDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealDate");
            txtAccount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtAccount");
            txtNotes = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtNotes");

            string[] selectValue = dropPayType.SelectedItem.Value.Split('|');
            if (selectValue[1] == "1" && txtDealID.Text.Trim() == "")
            {
                throw new Exception("您选择的支付方式必须输入交易号，请输入！");
            }
            tbl.Rows[i]["PDPD_DTCODE"] = dropDealType.SelectedValue;
            tbl.Rows[i]["PDPD_PAYTYPE"] = selectValue[0];
            tbl.Rows[i]["PDPD_PAYAMT"] = Convert.ToDecimal(txtPayAmount.Text.Trim());
            tbl.Rows[i]["PDPD_PAYDATE"] = Convert.ToDateTime(txtPayDate.Text.Trim());
            tbl.Rows[i]["PDPD_DEALID"] = txtDealID.Text.Trim();
            tbl.Rows[i]["PDPD_DEALDATE"] = Convert.ToDateTime(txtDealDate.Text.Trim());
            tbl.Rows[i]["PDPD_ACCOUNT"] = txtAccount.Text.Trim();
            tbl.Rows[i]["PDPD_NOTE"] = txtNotes.Text.Trim();
        }

    }

    /// <summary>
    /// 校验结算单主表的结算金额和结算单支付明细中支付金额总额是否相等
    /// </summary>
    /// <param name="tbl"></param>
    /// <param name="settleAmount"></param>
    /// <returns></returns>
    private bool ValidSettleAmount(DataTable tbl, decimal settleAmount)
    {
        if (tbl != null)
        {
            decimal amount = 0;
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                amount += Convert.ToDecimal(tbl.Rows[i]["PDPD_PAYAMT"]);
            }
            if (settleAmount >= amount)
            {
                decimal payAmount = Convert.ToDecimal(txtPayAmount.Text.Trim());
                if (payAmount > 0)
                {
                    return amount >= payAmount;
                }
                else
                {
                    return amount == payAmount;
                }
            }
            else
            {
                return false;
            }

        }
        else if (Convert.ToDecimal(txtReceiveMoneyAmount.Text.Trim()) == 0 && Convert.ToDecimal(txtPayAmount.Text.Trim()) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("Settlement.aspx");
    }

    private void BindDataListPayDocPayDetail(DataTable tbl)
    {
        dlistPayDocPayDetail.DataSource = tbl;
        dlistPayDocPayDetail.DataBind();
    }

    protected void DataList2_DDLCHANGE_Click(object sender, EventArgs e)
    {
        DropDownList dropDealType = (DropDownList)sender;
        DropDownList dropPayType = (DropDownList)dropDealType.Parent.FindControl("dropPayType");
        BindDropPayType(dropDealType.SelectedValue, dropPayType);
    }
}

